//
//  HomePageViewController.m
//  HotWord
//
//  Created by Rainbow on 9/8/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "HomePageViewController.h"
#import "MainMenuViewController.h"
#import "LoginViewController.h"
#import "HotWordAppDelegate.h"
#import "AdvertisingTableViewController.h"
#import "CacheData.h"
#import "PersistenceData.h"
#import "ServiceHelper.h"
#import "UserManager.h"
#import "PersonalInfoViewController.h"
#import "introduceViewController.h"
#import "MessageManager.h"
#import "UserInfoViewController.h"

@interface HomePageViewController()

- (void)showAdUpdateCount;
- (void)loadMainMenuViewController:(NSNumber *)index;

@end

@implementation HomePageViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [_infoBtn release];
    [_messageBtn release];
    [_advertisingBtn release];
    [_pageControl release];
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    //advertising btn
    [super viewDidLoad];
    _advertisingBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0 , 50, 50)];
    _advertisingBtn.clipsToBounds = NO;
    [_advertisingBtn setBackgroundImage:[UIImage imageNamed:@"news.png"] forState:UIControlStateNormal];
    _advertisingBtn.adjustsImageWhenHighlighted = NO;
    [_advertisingBtn setImage:[UIImage imageNamed:@"tap_light.png"] forState:UIControlStateHighlighted];
    [_advertisingBtn setImageEdgeInsets:UIEdgeInsetsMake(0, 25, 0, 25)];
    [_advertisingBtn addTarget:self action:@selector(tapOnAdvertisingBtn) forControlEvents:UIControlEventTouchUpInside];
    
    _infoBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 50, 50)];
    _infoBtn.adjustsImageWhenHighlighted = NO;
    [_infoBtn setBackgroundImage:[UIImage imageNamed:@"introduce_new.png"] forState:UIControlStateNormal];
    [_infoBtn setImage:[UIImage imageNamed:@"tap_light.png"] forState:UIControlStateHighlighted];
    [_infoBtn setImageEdgeInsets:UIEdgeInsetsMake(0, 25, 0, 25)];
    [_infoBtn addTarget:self action:@selector(tapOnInfoBtn) forControlEvents:UIControlEventTouchUpInside];
   
    _messageBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 50, 50)];
    _messageBtn.adjustsImageWhenHighlighted = NO;
    [_messageBtn setBackgroundImage:[UIImage imageNamed:@"messages.png.png"] forState:UIControlStateNormal];
    [_messageBtn setImage:[UIImage imageNamed:@"tap_light.png"] forState:UIControlStateHighlighted];
    [_messageBtn setImageEdgeInsets:UIEdgeInsetsMake(0, 25, 0, 25)];
    [_messageBtn addTarget:self action:@selector(tapOnMessageBtn) forControlEvents:UIControlEventTouchUpInside];
    
    
    CALayer *bottomLayer = [CALayer layer];
    [bottomLayer setFrame:CGRectMake(0,0, 320, 480)];
    [bottomLayer setContents:(id)[UIImage imageNamed:@"bottom.png"].CGImage];
    [self.view.layer addSublayer:bottomLayer];
    
    CALayer *coverLayer = [CALayer layer];
    [coverLayer setFrame:CGRectMake(0, 0, 320, 480)];
    [coverLayer setContents:(id)[UIImage imageNamed:@"first.png"].CGImage];
    [self.view.layer addSublayer:coverLayer];
    [self setScrollView];
    CALayer *shadowLayer = [CALayer layer];
    [shadowLayer setFrame:CGRectMake(0, 0, 320, 480)];
    [shadowLayer setContents:(id)[UIImage imageNamed:@"second.png"].CGImage];
    [self.view.layer addSublayer:shadowLayer];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(showMessageCount) name:NOTIFICATION_RECEIVE_MESSAGE object:nil];
    
    _pageControl = [[ITTPageView alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];
    [_pageControl setInitStateFromNib:3];
    _pageControl.center = self.view.center;
    _pageControl.top = 390;
    _pageControl.backgroundColor = [UIColor clearColor];
    _pageControl.currentPage = 0;
    [self.view addSubview:_pageControl];
    
}

-(void)viewWillAppear:(BOOL)animated
{

    [super viewWillDisappear:animated];
    HotWordAppDelegate *appDelegate= (HotWordAppDelegate *)[UIApplication sharedApplication].delegate;
    
    appDelegate.MainToolBar.hidden = NO;
    [[appDelegate.MainToolBar viewWithTag:707] removeFromSuperview];
    [[appDelegate.MainToolBar viewWithTag:808] removeFromSuperview];
    [[appDelegate.MainToolBar viewWithTag:909] removeFromSuperview];

    
    appDelegate.MainToolBar.frame=CGRectMake(0, 480, 320, 70);
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    [UIView setAnimationDelegate:self];
    [UIView setAnimationDuration:0.6];
    appDelegate.MainToolBar.frame=CGRectMake(0, 410, 320, 70);

    [UIView commitAnimations];
    
    [[appDelegate.MainToolBar viewWithTag:66]   removeFromSuperview];
    [[appDelegate.MainToolBar viewWithTag:77]   removeFromSuperview];
    [[appDelegate.MainToolBar viewWithTag:88]   removeFromSuperview];
    _advertisingBtn.left = 135;
    _advertisingBtn.top = 0;
    [appDelegate.MainToolBar addSubview:_advertisingBtn];
    
    _infoBtn.left = 190;
    _infoBtn.top = 0;
    [appDelegate.MainToolBar addSubview:_infoBtn];
    
    _messageBtn.left = 80;
    _messageBtn.top = 0;
    [appDelegate.MainToolBar addSubview:_messageBtn];
    [self showMessageCount];
    
    
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    NSDictionary *params = [NSDictionary dictionaryWithObject:[[PersistenceData sharedData] getAdUpdateTimestamp] forKey:@"time"];
    
    [self showAdUpdateCount];
    
    [[ServiceHelper sharedService] requestServerForMethod:HotWordRequestTypeGetAdvertising WithParameters:params AndCallBackScope:self AndSuccessSel:@"getAdvertisingSuccess" AndFailedSel:@"getAdvertisingFailed"];

}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [_advertisingBtn removeFromSuperview];
    [_infoBtn removeFromSuperview];
    [_messageBtn removeFromSuperview];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void)setScrollView
{
    UIScrollView *welcomeScrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(101, 0, 118, 480)];
    welcomeScrollView.showsHorizontalScrollIndicator = NO;
    [welcomeScrollView setDelegate:self];
    [welcomeScrollView setPagingEnabled:YES];
    [self.view addSubview:welcomeScrollView];
    
    for (int i = 0; i < 5; i++) {
        UIImageView *tempImgView = [[UIImageView alloc]initWithFrame:CGRectMake(i * 118, 0, 118, 480)];
        
        if (i == 3) {
            [tempImgView setImage:[UIImage imageNamed:@"image1.png"]];

        }
        else if (i == 4) {
            [tempImgView setImage:[UIImage imageNamed:@"image2.png"]];
            
        }
        else
        {
            [tempImgView setImage:[UIImage imageNamed:[NSString stringWithFormat:@"image%d.png",i+1]]];
        }
        
        //i, 0: iBT 2: SAT 3: GRE 4: iBT
        //(0: frieds 1:none) 2: SAT 3: GRE 4: iBT 5: friends
        
        if (i == 1 || i == 2 || i == 4) {
            
            tempImgView.tag = 10 + i;
            /*
            if (i == 0) {
                //tempImgView.tag = 14;
            }
             */
            if (i == 4) {
                tempImgView.tag = 11;
            }
            
            [tempImgView setUserInteractionEnabled:YES];
            UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTapGesture:)];
            tapGestureRecognizer.cancelsTouchesInView = NO;
            tapGestureRecognizer.delegate = self;
            [tempImgView addGestureRecognizer:tapGestureRecognizer];
            [tapGestureRecognizer release];
        }
    
        if (i == 0 || i == 3) {
            tempImgView.tag = 13;
            
            [tempImgView setUserInteractionEnabled:YES];
            UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTapGesture:)];
            tapGestureRecognizer.cancelsTouchesInView = NO;
            tapGestureRecognizer.delegate = self;
            [tempImgView addGestureRecognizer:tapGestureRecognizer];
            [tapGestureRecognizer release];
        }
        
        [welcomeScrollView addSubview:tempImgView];
        [tempImgView release];
        
    }
    
    [welcomeScrollView setContentSize:CGSizeMake(5*118, 480)];
    [welcomeScrollView scrollRectToVisible:CGRectMake(118*3, 0, 118, 480) animated:NO];
    [welcomeScrollView release];
    
    
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    NSLog(@"scroll Index: %f",scrollView.contentOffset.x/118);
    _pageControl.currentPage = scrollView.contentOffset.x/118;
    if (scrollView.contentOffset.x == 0) {
        [scrollView scrollRectToVisible:CGRectMake(118*3, 0, 118, 156) animated:NO];
    }else if(scrollView.contentOffset.x == 118*4) {
        [scrollView scrollRectToVisible:CGRectMake(118, 0, 118, 156) animated:NO];
        _pageControl.currentPage = 1;
    }else if(scrollView.contentOffset.x == 118*3) {
        _pageControl.currentPage = 0;
    }
}

- (void)switchCategoryInMainThread:(NSNumber *)index
{
    
    if ([[PersistenceData sharedData] getLetterByName:[[CacheData sharedData].letters objectAtIndex:0]]) {
        [self loadMainMenuViewController:index];
    }
    
    else
    {
        [[PersistenceData sharedData] setUpdateTimestamp:[[NSDate date] timeIntervalSince1970]];
        NSMutableDictionary *params = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
        [params setObject:[NSString stringWithFormat:@"%d", [index intValue]- 11] forKey:@"category"];
        [params setObject:@"A" forKey:@"letter"];
        [[ServiceHelper sharedService] requestServerForMethod:HotWordRequestTypeGetWords WithParameters:params AndCallBackScope:self AndSuccessSel:@"onSuccess:" AndFailedSel:@"onFailed:"];
        
        _loadingWords = YES;
    }
}

//qiji

- (void)setCategoryInSubThread:(NSNumber *)index
{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    if ([index intValue] == 11) {
        [[CacheData sharedData] setCurrentCategory:SAT_WORDS];
    }
    else if([index intValue] == 12){
        [[CacheData sharedData] setCurrentCategory:GRE_WORDS];
    }
//    else if([index intValue] == 13){
//        [[CacheData sharedData] setCurrentCategory:IBT_WORDS];
//    }
    [self performSelectorOnMainThread:@selector(switchCategoryInMainThread:) withObject:index waitUntilDone:YES];
    [pool release];
}

- (void)tapOnMenu:(NSInteger )index
{
    if (_loadingWords) {
        return;
    }
    
    [[HTActivityIndicator currentIndicator] displayActivity:@"正在加载词库"];
    _loadingWords = YES;
    
    [self performSelectorInBackground:@selector(setCategoryInSubThread:) withObject:[NSNumber numberWithInt:index]];  
}


- (void)loadMainMenuViewController:(NSNumber *)index
{
    [UIView beginAnimations:nil context:nil];
	[UIView setAnimationDuration:0.5f];
	[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
	[UIView setAnimationRepeatAutoreverses:NO];
	[UIView setAnimationTransition:UIViewAnimationTransitionFlipFromRight forView:[UIApplication sharedApplication].keyWindow cache:NO];
    MainMenuViewController *mainMenuViewController = [[MainMenuViewController alloc] init];
    [self.navigationController pushViewController:mainMenuViewController animated:NO];
    [mainMenuViewController release];
    [UIView commitAnimations];
    
    _loadingWords = NO;
}

-(void)onSuccess:(NSObject *)result
{
    [UIView beginAnimations:nil context:nil];
	[UIView setAnimationDuration:0.5f];
	[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
	[UIView setAnimationRepeatAutoreverses:NO];
	[UIView setAnimationTransition:UIViewAnimationTransitionFlipFromRight forView:[UIApplication sharedApplication].keyWindow cache:NO];
    MainMenuViewController *mainMenuViewController = [[MainMenuViewController alloc] init];
    [self.navigationController pushViewController:mainMenuViewController animated:NO];
    [mainMenuViewController release];
    [UIView commitAnimations];
    _loadingWords = NO;
}

-(void)onFailed:(NSObject *)result
{
    [[HTActivityIndicator currentIndicator] displayMessage:@"加载失败，请检查网络！"];
    _loadingWords = NO;
}

//qiji
- (void)handleTapGesture:(UITapGestureRecognizer *)recognizer
{
    if (recognizer.view.tag == 11 || recognizer.view.tag == 12) {
        [self tapOnMenu:recognizer.view.tag];
    }else if(recognizer.view.tag ==13){
        [self loadLoginViewController];
    }

}

- (void)loadLoginViewController{
    
    
    [UIView beginAnimations:nil context:nil];
	[UIView setAnimationDuration:0.5f];
	[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
	[UIView setAnimationRepeatAutoreverses:NO];
	[UIView setAnimationTransition:UIViewAnimationTransitionFlipFromRight forView:[UIApplication sharedApplication].keyWindow cache:NO];
    if ([UserManager sharedManager].currentUser) {
//        PersonalInfoViewController *personalInfoViewController = [[[PersonalInfoViewController alloc] init] autorelease];
//        [self.navigationController pushViewController:personalInfoViewController animated:NO];
        UserInfoViewController *userInfoViewController = [[UserInfoViewController alloc] init];
        [self.navigationController pushViewController:userInfoViewController animated:NO];
    }
    else {
        LoginViewController *loginViewController = [[[LoginViewController alloc] init] autorelease];
        [self.navigationController pushViewController:loginViewController animated:NO];
    }
    HotWordAppDelegate *appDelegate= (HotWordAppDelegate *)[UIApplication sharedApplication].delegate;
    appDelegate.MainToolBar.hidden = YES;
    [UIView commitAnimations];
}

- (void)tapOnInfoBtn
{
    [UIView beginAnimations:nil context:nil];
	[UIView setAnimationDuration:0.5f];
	[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
	[UIView setAnimationRepeatAutoreverses:NO];
	[UIView setAnimationTransition:UIViewAnimationTransitionFlipFromRight forView:[UIApplication sharedApplication].keyWindow cache:NO];
    introduceViewController *introduceview = [[[introduceViewController alloc] init] autorelease];
    [self.navigationController pushViewController:introduceview animated:NO];
	[UIView commitAnimations];
}

- (void)tapOnAdvertisingBtn
{
    
    [UIView beginAnimations:nil context:nil];
	[UIView setAnimationDuration:0.5f];
	[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
	[UIView setAnimationRepeatAutoreverses:NO];
	[UIView setAnimationTransition:UIViewAnimationTransitionFlipFromRight forView:[UIApplication sharedApplication].keyWindow cache:NO];
    AdvertisingTableViewController *advertisingTableViewController = [[[AdvertisingTableViewController alloc] init] autorelease];
    [self.navigationController pushViewController:advertisingTableViewController animated:NO];
    
	[UIView commitAnimations];
    [[_advertisingBtn viewWithTag:100] removeFromSuperview];
}

- (void)tapOnMessageBtn
{
    [self loadLoginViewController];
}

- (void)getAdvertisingSuccess
{
    [self showAdUpdateCount];
}

- (void)getAdvertisingFailed
{
    
}

- (void)showMessageCount
{
    [[_messageBtn viewWithTag:100] removeFromSuperview];
    NSString *newMessageCount = [NSString stringWithFormat:@"%d", [MessageManager sharedManager].newMessageCount];
    if ([MessageManager sharedManager].newMessageCount > 10)
    {
        newMessageCount = @"n";
    }
    
    if ([MessageManager sharedManager].newMessageCount > 0) {
        UIImageView *indicatorView = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"indicator.png"]] autorelease];
        indicatorView.frame = CGRectMake(0, 0, 50, 50);
        indicatorView.tag = 100;
        
        UILabel *countLabel = [[[UILabel alloc] initWithFrame:CGRectMake(14, 19, 30, 14)] autorelease];
        countLabel.text = newMessageCount;
        countLabel.textAlignment = UITextAlignmentCenter;
        countLabel.font = [UIFont systemFontOfSize:20];
        countLabel.textColor = [UIColor whiteColor];
        countLabel.backgroundColor = [UIColor clearColor];
        
        [indicatorView addSubview:countLabel];
        
        [_messageBtn addSubview:indicatorView];
    }
}

- (void)showAdUpdateCount
{
    [[_advertisingBtn viewWithTag:100] removeFromSuperview];
    NSString *adUpdateCount = [[PersistenceData sharedData] getAdUpdateCount];
    if (adUpdateCount && ![@"0" isEqualToString:adUpdateCount]) {
        UIImageView *indicatorView = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"indicator.png"]] autorelease];
        indicatorView.frame = CGRectMake(0, 0, 50, 50);
        indicatorView.tag = 100;
        
        UILabel *countLabel = [[[UILabel alloc] initWithFrame:CGRectMake(14, 19, 30, 14)] autorelease];
        countLabel.text = adUpdateCount;
        countLabel.textAlignment = UITextAlignmentCenter;
        countLabel.font = [UIFont systemFontOfSize:20];
        countLabel.textColor = [UIColor whiteColor];
        countLabel.backgroundColor = [UIColor clearColor];
        
        [indicatorView addSubview:countLabel];
        
        [_advertisingBtn addSubview:indicatorView];
    }
}

@end
